/*----------------------------------------------------------------------
  File name: "RTC.c"

  Driver for DS1305 Real Time Clock.

  Wiring:
  [Mega32]  [RTC1305]
  Vcc          Vcc
  GND          GND
  SS=PB.4      CE  
  MOSI=PB.5    SI  
  MISO=PB.6    SO 
  SCK=PB.7     CLK

  Henning Hargaard, February 2, 2012
-----------------------------------------------------------------------*/
#include <avr/io.h>
#include "Clock.h"
#include "SPI.h"

#include "uart.h"

// Converts binary number to BCD
unsigned char BCD(unsigned char binary)
{
	unsigned char BCDresult;
	BCDresult = (binary/10)<<4;
	BCDresult |= binary%10;
	return(BCDresult);  
}

// Converts BCD number to binary
unsigned char FromBCD(unsigned char BCDnumber)
{
  return(((BCDnumber>>4)*10) + (BCDnumber & 0x0F));
}

void Clock_Write(unsigned char addr,unsigned char byte)
{

	
	SPI_Start(CLOCK_ADDR);
	SPI_Write(addr);
	SPI_Write(byte);
	SPI_End();
	

}

void Clock_Init()
{
  // Enable clock, remove write protection, no interrupts enabled
  Clock_Write(RTC_CONTROL_WRITE,0b00000000);   
}



unsigned char Clock_Read(unsigned char addr)
{
	unsigned char ret;
	
	SPI_Start(CLOCK_ADDR);
	SPI_Write(addr);
	ret=SPI_Read();
	SPI_End();
	
	return ret;
}


// Sets clock registers according to the parameters 
void Clock_SetDate(date_t d)
{
  Clock_Write(0x86,BCD(d.year));
  Clock_Write(0x85,BCD(d.month));
  Clock_Write(0x83,d.day);
  Clock_Write(0x82,BCD(d.hour & 0x2F));
  Clock_Write(0x81,BCD(d.minutes));
  Clock_Write(0x80,BCD(d.seconds));          
}              


date_t Clock_Date()
{
	date_t date;
	
	date.year=FromBCD( Clock_Read(0x06) );
	date.month=FromBCD( Clock_Read(0x05) );
	date.day=FromBCD( Clock_Read(0x03) );
	
	date.hour=FromBCD( Clock_Read(0x02));
	date.minutes=FromBCD( Clock_Read(0x01) );
	date.seconds=FromBCD( Clock_Read(0x00) );
	
	return date;
}

date_t	Clock_CreateDate(unsigned char year, unsigned char month, unsigned char day,
              unsigned char hour, unsigned char minutes, unsigned char seconds)
{
	date_t d;
	d.year=year;
	d.month=month;
	d.day=day;
	d.hour=hour;
	d.minutes=minutes;
	d.seconds=seconds;	
	return d;	  
}				  
			  